const net = require('net');

/**
 * 检测端口是否被使用
 * @param {number}} port 
 * @returns 返回可用的一个端口
 */
function checkedPortIsUsed(port) {
	return new Promise((resolve) => {
		const server = net.createServer().listen(port);
		server.on('listening', () => {
			server.close()
			resolve(true)
		})
		server.on('error', function (err) {
			if (err.code === 'EADDRINUSE') {
				resolve(false);
			}
		});
	})
}

async function getAvailablePort (port = 3000) {
	const isGenPort = false
	while(!isGenPort) {
		const result = await checkedPortIsUsed(port)
		if (result) {
			return port
		}
		port ++;
	}
}

module.exports = getAvailablePort